package com.zzg.mybatis.generator.plugins;

import java.util.List;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;


/**
 *
 * 功能描述：jsr303 代码生成插件
 *
 * <p>修改历史：(修改人，修改时间，修改原因/内容)</p>
 */
public class HibernateJSR303Plugin extends PluginAdapter {

	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}

	@Override
	public boolean modelFieldGenerated(Field field,
			TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
			IntrospectedTable introspectedTable, ModelClassType modelClassType) {

		boolean isNotBlank = false; //是否已是非空字段
		if (false == introspectedColumn.isNullable()) {
			if (false == introspectedColumn.isIdentity()) {
				boolean isPrimarkKey = false;//是否为主键
				for(IntrospectedColumn column : introspectedTable.getPrimaryKeyColumns()) {
					if(introspectedColumn==column) {
						isPrimarkKey = true;
					}
				}
				if(!isPrimarkKey) {
					isNotBlank = true;
					topLevelClass.addImportedType("org.hibernate.validator.constraints.NotBlank");
					field.addAnnotation("@NotBlank");
					topLevelClass.addImportedType("org.hibernate.validator.constraints.Range");
					field.addAnnotation("@Range(min = 1, max = "
							+ introspectedColumn.getLength()
							+ " , message = \"长度为{min}-{max}个字符\")");
				}
			}
		}

		if (!isNotBlank && introspectedColumn.isStringColumn()) {
			topLevelClass.addImportedType("org.hibernate.validator.constraints.Range");
			field.addAnnotation("@Range(max = "
					+ introspectedColumn.getLength()
					+ " , message = \"长度为最大{max}个字符\")");
		}
//		System.out.println(introspectedColumn.getJdbcTypeName()+'-'+introspectedColumn.getJdbcType());

		return super.modelFieldGenerated(field, topLevelClass,
				introspectedColumn, introspectedTable, modelClassType);
	}

}
